import * as storageCenter from "@/common/storageCenter.js"
/**
 * 返回加小数点的金额
 * @param {*} num 
 * @returns 
 */
export function formatNumber(num) {
	num = Number(num);
	if (isNaN(num)) return '0.00';
	num = num.toFixed(2); // 保留两位小数
	// 检查是否已经是两位小数，如果不是则添加'.00'
	if (num.toString().split('.')[1].length < 2) {
		num += '.00';
	}
	return num;
}

/** 加法函数，用来得到精确的加法结果
** 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
** 调用：accAdd(arg1,arg2)
** 返回值：arg1加上arg2的精确结果
**/
export function accAdd (arg1, arg2) {
	if(!arg1){
		arg1 = 0
	}
	if(!arg2){
		arg2 = 0
	}
      let r1
      let r2
      let m
      let c
      try {
        	r1 = arg1.toString().split('.')[1].length
      } catch (e) {
        	r1 = 0
      }
      try {
   			r2 = arg2.toString().split('.')[1].length
      } catch (e) {
        	r2 = 0
      }
      c = Math.abs(r1 - r2)
      m = Math.pow(10, Math.max(r1, r2))
	if (c > 0) {
        let cm = Math.pow(10, c)
        if (r1 > r2) {
          arg1 = Number(arg1.toString().replace('.', ''))
          arg2 = Number(arg2.toString().replace('.', '')) * cm
        } else {
          arg1 = Number(arg1.toString().replace('.', '')) * cm
          arg2 = Number(arg2.toString().replace('.', ''))
        }
 	 } else {
   	 arg1 = Number(arg1.toString().replace('.', ''))
   	 arg2 = Number(arg2.toString().replace('.', ''))
	 }
  return (arg1 + arg2) / m
}

export const StorageSystemInfo = function() {
	let systemInfo = null;
	try {
		systemInfo = storageCenter.get(storageCenter.keys.StorageSystemInfo)
	} catch (e) {}
	if (systemInfo) {
		return systemInfo
	} else {
		// #ifdef MP-WEIXIN
		let window_info = uni.getWindowInfo();
		let device_info = uni.getDeviceInfo()
		let app_baseInfo = uni.getAppBaseInfo()
		systemInfo = {
			...window_info,
			...device_info,
			...app_baseInfo
		}
		// #endif
		// #ifndef MP-WEIXIN
		systemInfo = uni.getSystemInfoSync();
		// #endif
		storageCenter.set(storageCenter.keys.StorageSystemInfo, systemInfo)
		return systemInfo
	}
}

// 1rpx 换算成 px
export const px_from_rpx = function(rpx) {
	return StorageSystemInfo().windowWidth / 750 * (rpx ? rpx : 0);
}
// 1px 换算成 rpx
export const rpx_from_px = function(px) {
	return 750 / StorageSystemInfo().windowWidth * (px ? px : 0);
}
